var mysql = require('mysql');
// 创建数据库连接池
var pool  = mysql.createPool({
    host     : '192.168.60.3',
    //  host     : '192.168.120.14',
    port     : 3306,
    user     : 'esr',
    password : 'esr16888',
    database : 'nutch'
});
var conn;

module.exports.pool = pool;
module.exports.getConn = getConn;
module.exports.handleError = handleError;

function getConn() {
    /*conn = mysql.createConnection({
        host: 'localhost',
        user: 'nodejs',
        password: 'nodejs',
        database: 'nodejs',
        port: 3306
    });*/

    return conn;
}


function handleError () {
    conn = mysql.createConnection({
        host: 'localhost',
        user: 'nodejs',
        password: 'nodejs',
        database: 'nodejs',
        port: 3306
    });

    //连接错误，2秒重试
    conn.connect(function (err) {
        if (err) {
            console.log('error when connecting to db:', err);
            setTimeout(handleError , 2000);
        }
    });

    conn.on('error', function (err) {
        console.log('db error', err);
        // 如果是连接断开，自动重新连接
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            handleError();
        } else {
            throw err;
        }
    });
}
